import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

# 设置指数分布的参数 λ
lambda_param = 2

# 设置样本容量 n 的值
n_values = [2, 20, 200]

# 设置随机数的组数（即试验次数）
num_simulations = 10000

# 创建一个图形窗口，包含 3 个子图
fig, axs = plt.subplots(1, len(n_values), figsize=(18, 5))

# 遍历每个 n 值
for i, n in enumerate(n_values):
    # 初始化一个数组来存储样本均值
    sample_means = np.zeros(num_simulations)
    
    # 进行 num_simulations 次试验
    for j in range(num_simulations):
        # 生成一个大小为 n 的指数分布随机数样本
        sample = np.random.exponential(1/lambda_param, n)
        # 计算该样本的均值
        sample_means[j] = np.mean(sample)
    
    # 计算样本均值的均值和标准差（用于绘制正态密度曲线）
    mean_of_means = np.mean(sample_means)
    std_of_means = np.std(sample_means, ddof=1)  # 使用无偏估计计算标准差
    
    # 绘制样本均值的直方图
    axs[i].hist(sample_means, bins=50, density=True, alpha=0.6, color='g', edgecolor='black')
    
    # 绘制正态密度曲线
    xmin, xmax = plt.xlim()
    x = np.linspace(xmin, xmax, 100)
    p = norm.pdf(x, mean_of_means, std_of_means)
    axs[i].plot(x, p, 'k', linewidth=2)
    
    # 设置标题和标签
    axs[i].set_title(f'n = {n}')
    axs[i].set_xlabel('Sample Mean')
    axs[i].set_ylabel('Density')
    
    # 显示均值和标准差
    axs[i].text(0.05, 0.9, f'Mean = {mean_of_means:.4f}\nStd = {std_of_means:.4f}',
                transform=axs[i].transAxes, fontsize=12,
                verticalalignment='top', bbox={'facecolor': 'white', 'alpha': 0.5, 'pad': 10})

# 调整子图之间的间距
plt.tight_layout()

# 显示图形
plt.show()